<script setup lang="ts">
import { ref, watch, nextTick } from 'vue'
import {
  ElDialog,
  ElForm,
  ElFormItem,
  ElInput,
  ElSelect,
  ElOption,
  ElMessage,
  ElDatePicker,
  ElUpload,
  ElRow,
  ElCol,
  ElMessageBox
} from 'element-plus'
import { Plus, Delete } from '@element-plus/icons-vue'
import { BaseButton } from '@/components/Button'
import { uploadFileApi } from '@/api/upload'
import { getOrderEnumApi } from '@/api/order'
import { getTransferDetailApi, updateTransferApi, warehouseInApi } from '@/api/warehouse'

const props = defineProps({
  dialogVisible: {
    type: Boolean,
    default: false
  },
  row: {
    type: Object,
    default: () => ({})
  }
})

const emit = defineEmits(['update:dialogVisible', 'refresh'])

const formRef = ref()

const formData = ref({
  logistics_company: '' as string | number,
  logistics_no: '',
  delivery_time: '',
  arrival_time: '',
  cost: [] as any[],
  transaction_currency_id: 214,
  logistics_cert: [] as any[],
  remark: '',
  arrival_batch: ''
})

// 物流公司选项列表
const logisticsCompanyList = ref<Array<{ value: string | number; label: string }>>([])
const logisticsCompanyTree = ref<Array<Record<string, any>>>([])
const loading = ref(false)

const rules = {
  logistics_company: [{ required: true, message: '请选择物流公司', trigger: 'change' }],
  logistics_no: [
    {
      required: false,
      message: '请输入物流单号',
      trigger: 'blur',
      validator: (rule, value, callback) => {
        // 动态校验：只有在入库时才必填
        if (props.row && !props.row.warehouseIn && !value) {
          callback(new Error('请输入物流单号'))
        } else {
          callback()
        }
      }
    }
  ],
  delivery_time: [{ required: true, message: '请选择发货时间', trigger: 'change' }],
  cost: [
    {
      required: props.row.warehouseIn ? true : false,
      trigger: 'blur',
      validator: (rule, value, callback) => {
        if (!Array.isArray(value) || value.length === 0) {
          if (!props.row.warehouseIn) {
            callback(new Error('请添加成本'))
          } else {
            callback()
          }
        } else {
          callback()
        }
      }
    }
  ],
  arrival_batch: [{ required: true, message: '请输入入库批次', trigger: 'blur' }]
}

// 获取调拨详情数据
const fetchTransferDetail = async (id: string | number) => {
  if (!id) return

  loading.value = true
  try {
    const res = await getTransferDetailApi(id)
    if (res.code === 0 && res.data) {
      const detail = res.data as any

      // 适配表单数据
      formData.value = {
        logistics_company: detail.company_id,
        logistics_no: detail.logistics_no?.toString() || '',
        delivery_time: detail.ship_date || '',
        arrival_time: detail.arrival_date || '',
        cost: Array.isArray(detail.cost) ? detail.cost : [],
        transaction_currency_id: detail.transaction_currency_id || 214,
        logistics_cert:
          detail.logistics_voucher_info?.map((item, index) => ({
            id: item.id,
            uid: `existing_${item.id}_${index}`,
            name: `image_${item.id}`,
            url: item.url,
            response: {
              data: {
                id: item.id,
                url: item.url
              }
            }
          })) || [],
        remark: detail.notes || '',
        arrival_batch: ''
      }

      console.log('获取到的详情数据:', detail)
      console.log('设置的文件列表:', formData.value.logistics_cert)
    }
  } catch (error) {
    console.error('获取调拨详情失败:', error)
    ElMessage.error('获取调拨详情失败')
  } finally {
    loading.value = false
  }
}

// 获取物流公司下拉数据
const operatorOptions = ref<Record<string, any>>({})
const fetchLogisticsCompanyOptions = async () => {
  try {
    const resOrderEnum = await getOrderEnumApi()
    if (resOrderEnum?.data) {
      operatorOptions.value = resOrderEnum.data
      logisticsCompanyList.value = resOrderEnum.data.logistics_company || []
      logisticsCompanyTree.value =
        resOrderEnum.data.logistics_company_tree || resOrderEnum.data.logistics_company || []
    }
  } catch (error) {
    console.error('获取物流公司列表失败:', error)
  }
}

const handleClose = () => {
  formRef.value?.resetFields()
  emit('update:dialogVisible', false)
}
const uploadRef = ref<any>(null)
const handleConfirm = async () => {
  if (!formRef.value) return
  try {
    await formRef.value.validate()
    // 校验成本数组
    if (Array.isArray(formData.value.cost)) {
      for (let i = 0; i < formData.value.cost.length; i++) {
        const item = formData.value.cost[i]
        if (!item.type || item.amount === '' || item.amount === null || item.amount === 0) {
          ElMessage.warning('成本类型、金额不能为空')
          return
        }
      }
    }
    // 优化文件ID提取逻辑
    // const fileIds = formData.value.logistics_cert
    //   .filter((file: any) => {
    //     console.log('文件检查:', file, file.response)
    //     return file.response?.data?.id || file.id
    //   })
    //   .map((file: any) => file.response?.data?.id || file.id)
    //   .filter((id) => id) // 过滤掉空值

    // console.log('提取的文件ID:', fileIds)
    let result = await uploadRef.value?.uploadImg()
    console.log('result', result)
    if (result) {
      ElMessage.warning('上传中,请稍等')
      return
    }
    console.log('formData.value.logistics_cert', formData.value.logistics_cert)
    // 调用更新接口
    const params = {
      id: props.row.id,
      company_id: Number(formData.value.logistics_company),
      logistics_no: formData.value.logistics_no,
      logistics_voucher: formData.value.logistics_cert.map((e) => e.id).join(','),
      ship_date: formData.value.delivery_time,
      arrival_date: formData.value.arrival_time,
      cost: formData.value.cost,
      notes: formData.value.remark
    } as any

    console.log('提交参数:', params, props.row.warehouseIn)
    if (props.row.warehouseIn) {
      handleWarehouseIn(params)
      return
    }
    const res = await updateTransferApi(params)
    if (res.code === 0) {
      ElMessage.success('编辑成功')
      emit('refresh')
      handleClose()
    } else {
      ElMessage.error('编辑失败')
    }
  } catch (error) {
    console.error('提交失败:', error)
    ElMessage.error('提交失败')
  }
}

const removeCostRow = (index: number) => {
  ElMessageBox.confirm('确定要删除该成本项吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(() => {
      formData.value.cost.splice(index, 1)
    })
    .catch(() => {
      // 用户取消，无操作
    })
}

const addCostRow = () => {
  formData.value.cost.push({ type: '', amount: '', transaction_currency_id: 214 })
}
//上传成功以后回调
const handleUploadCallback = (val: any) => {
  formData.value.logistics_cert.push(...val)
}
const handleWarehouseIn = async (params: any) => {
  let res = await warehouseInApi({
    ...params,
    arrival_batch: formData.value.arrival_batch
  })
  console.log('res', res)
  if (res.code == 0) {
    ElMessage.success('入库成功')
    emit('refresh')
    handleClose()
  }
}
// 监听弹窗显示状态，获取物流公司列表和详情数据
const detailDialogVisible = ref(false)
watch(
  () => props.dialogVisible,
  async (newVal) => {
    detailDialogVisible.value = false
    console.log('props', props.row)
    if (newVal) {
      await fetchLogisticsCompanyOptions()
      // 如果有id，则获取详情数据
      if (props.row?.id) {
        await fetchTransferDetail(props.row.id)
      }
      detailDialogVisible.value = true
    }
  }
)

// 监听row变化，获取详情数据
watch(
  () => props.row,
  async (newVal, oldVal) => {
    if (newVal && Object.keys(newVal).length > 0) {
      // 只有当row的id发生变化时才重置表单和获取详情
      if (!oldVal || newVal.id !== oldVal.id) {
        // 先重置表单
        formData.value = {
          logistics_company: '',
          logistics_no: '',
          delivery_time: '',
          arrival_time: '',
          cost: [] as any[],
          transaction_currency_id: 214,
          logistics_cert: [],
          remark: '',
          arrival_batch: ''
        }

        // 如果弹窗是打开状态且有id，则获取详情数据
        if (props.dialogVisible && newVal.id) {
          await fetchTransferDetail(newVal.id)
        }
      }
    }
  },
  { immediate: true }
)
</script>

<template>
  <ElDialog
    :model-value="dialogVisible"
    :title="row.warehouseIn ? '入库调拨单' : '编辑调拨单'"
    width="800px"
    :close-on-click-modal="false"
    @close="handleClose"
    v-loading="loading"
  >
    <ElForm ref="formRef" :model="formData" :rules="rules" label-width="100px" class="edit-form">
      <ElRow :gutter="20">
        <ElCol :span="12">
          <ElFormItem label="物流公司" prop="logistics_company">
            <el-tree-select
              v-model="formData.logistics_company"
              :data="logisticsCompanyTree"
              :props="{
                children: 'children',
                label: 'name',
                value: 'id',
                disabled: (data) => data.company_type === 1
              }"
              placeholder="请选择物流公司"
              clearable
              :render-after-expand="false"
              :check-strictly="true"
              :default-expand-all="true"
              style="width: 100%"
            />
          </ElFormItem>
        </ElCol>
        <ElCol :span="12">
          <ElFormItem label="物流单号" prop="logistics_no">
            <ElInput v-model="formData.logistics_no" placeholder="请输入物流单号" />
          </ElFormItem>
        </ElCol>
        <ElCol :span="12">
          <ElFormItem label="发货时间" prop="delivery_time">
            <ElDatePicker
              v-model="formData.delivery_time"
              type="datetime"
              placeholder="请选择发货时间"
              style="width: 100%"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              disabled
            />
          </ElFormItem>
        </ElCol>
        <ElCol :span="12">
          <ElFormItem label="到货时间" prop="arrival_time">
            <ElDatePicker
              v-model="formData.arrival_time"
              type="datetime"
              placeholder="请选择到货时间"
              style="width: 100%"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              disabled
            />
          </ElFormItem>
        </ElCol>
        <ElCol :span="24">
          <ElFormItem label="成本" prop="cost">
            <div class="flex flex-col">
              <div
                v-for="(item, index) in formData.cost"
                :key="item.type"
                class="cost-row"
                style="display: flex; align-items: center; margin-bottom: 8px"
              >
                <el-select
                  v-model="item.type"
                  placeholder="请选择成本类型"
                  style="width: 140px; margin-right: 8px"
                >
                  <el-option
                    v-for="option in operatorOptions.costing"
                    :key="option.value"
                    :label="option.label"
                    :value="option.value"
                    :disabled="formData.cost.some((c, i) => c.type === option.value && i !== index)"
                  />
                </el-select>
                <el-input-number
                  v-model="item.amount"
                  :min="0"
                  :max="999999"
                  placeholder="金额"
                  style="width: 140px; margin-right: 8px"
                />
                <el-select
                  v-model="item.transaction_currency_id"
                  placeholder="币种"
                  style="width: 140px; margin-right: 8px"
                >
                  <el-option
                    v-for="currencyItem in operatorOptions.currency"
                    :key="currencyItem.value"
                    :label="currencyItem.label"
                    :value="currencyItem.value"
                  />
                </el-select>
                <el-button type="danger" @click="removeCostRow(index)"> 删除 </el-button>
              </div>
              <div class="flex items-center">
                <el-button type="primary" @click="addCostRow"> 添加 </el-button>
              </div>
            </div>
          </ElFormItem>
        </ElCol>
      </ElRow>

      <ElFormItem label="物流凭证">
        <UploadFilesBase
          v-if="detailDialogVisible"
          ref="uploadRef"
          class="w-full"
          :directory="2"
          :limit="99"
          :fileListMap="formData.logistics_cert"
          @upload-success-res="handleUploadCallback"
        />
      </ElFormItem>

      <ElFormItem label="备注">
        <ElInput
          v-model="formData.remark"
          type="textarea"
          :rows="3"
          placeholder="这里编辑备注信息这里编辑备注信息"
        />
      </ElFormItem>
      <ElFormItem label="入库批次" prop="arrival_batch" v-if="row.warehouseIn">
        <ElInput v-model="formData.arrival_batch" placeholder="请输入" maxlength="100" />
      </ElFormItem>
    </ElForm>

    <template #footer>
      <BaseButton @click="handleClose">取消</BaseButton>
      <BaseButton type="primary" @click="handleConfirm" v-if="!row.warehouseIn">确认</BaseButton>
      <BaseButton type="primary" @click="handleConfirm" v-if="row.warehouseIn">入库</BaseButton>
    </template>
  </ElDialog>
</template>

<style scoped lang="less">
.edit-form {
  .el-form-item {
    margin-bottom: 18px;
  }
}

.upload-cert-center {
  display: flex;
  height: 100%;
  font-size: 14px;
  color: #999;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.el-upload-list__item {
  position: relative;

  .el-upload-list__item-thumbnail {
    width: 100%;
    height: 100%;
    object-fit: cover;
  }

  .el-upload-list__item-actions {
    position: absolute;
    inset: 0;
    display: flex;
    align-items: center;
    justify-content: center;
    background: rgb(0 0 0 / 50%);
    opacity: 0;
    transition: opacity 0.3s;

    &:hover {
      opacity: 1;
    }

    .el-upload-list__item-delete {
      font-size: 20px;
      color: #fff;
      cursor: pointer;

      &:hover {
        color: #f56c6c;
      }
    }
  }

  &:hover .el-upload-list__item-actions {
    opacity: 1;
  }
}
</style>
